/**
 * 通用js方法封装处理
 * Copyright (c) 2019 ruoyi
 */
// 人民币小写转大写
export function convertCurrencyToChinese(currencyDigits) {
	// 验证输入是否为有效数字
	if (isNaN(currencyDigits) || currencyDigits === '') {
	  return 'a';
	}
	
	// 处理负数
	let isNegative = false;
	if (currencyDigits < 0) {
	  isNegative = true;
	  currencyDigits = Math.abs(currencyDigits);
	}
	
	// 最大处理的数字（万亿）
	if (currencyDigits > 9999999999999.99) {
	  return 'b';
	}
	
	// 定义中文数字和单位
	const CN_NUMBERS = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
	const CN_INTEGER_UNITS = ['', '拾', '佰', '仟'];
	const CN_DECIMAL_UNITS = ['角', '分'];
	const CN_GROUP_UNITS = ['', '万', '亿', '万亿'];
	
	// 将数字转为字符串，并处理小数点
	let currencyStr = currencyDigits.toString();
	let integerPart = '';
	let decimalPart = '';
	
	if (currencyStr.indexOf('.') === -1) {
	  integerPart = currencyStr;
	  decimalPart = '';
	} else {
	  const parts = currencyStr.split('.');
	  integerPart = parts[0];
	  decimalPart = parts[1].substring(0, 2); // 只取小数点后两位
	}
	
	// 处理整数部分
	let integerChinese = '';
	if (parseInt(integerPart, 10) > 0) {
	  let zeroCount = 0;
	  const integerLength = integerPart.length;
	  
	  for (let i = 0; i < integerLength; i++) {
		const digit = parseInt(integerPart.charAt(i), 10);
		const pos = integerLength - i - 1;
		const unitIndex = pos % 4;
		const groupIndex = Math.floor(pos / 4);
		
		if (digit === 0) {
		  zeroCount++;
		} else {
		  if (zeroCount > 0) {
			integerChinese += CN_NUMBERS[0];
			zeroCount = 0;
		  }
		  integerChinese += CN_NUMBERS[digit] + CN_INTEGER_UNITS[unitIndex];
		}
		
		if (unitIndex === 0 && zeroCount < 4) {
		  integerChinese += CN_GROUP_UNITS[groupIndex];
		}
	  }
	  
	  integerChinese += '元';
	}
	
	// 处理小数部分
	let decimalChinese = '';
	if (decimalPart !== '') {
	  for (let i = 0; i < decimalPart.length; i++) {
		const digit = parseInt(decimalPart.charAt(i), 10);
		if (digit !== 0) {
		  decimalChinese += CN_NUMBERS[digit] + CN_DECIMAL_UNITS[i];
		}
	  }
	}
	
	// 处理特殊情况
	if (integerChinese === '' && decimalChinese === '') {
	  return '零元整';
	}
	
	if (decimalChinese === '') {
	  decimalChinese = '整';
	}
	
	// 拼接结果
	let result = integerChinese + decimalChinese;
	
	// 处理负数
	if (isNegative) {
	  result = '负' + result;
	}
	
	return result;
  }
// s
// 生成UUID
export function generateUUID() {
	var d = new Date().getTime(); //Timestamp
	var d2 = (performance && performance.now && (performance.now() * 1000)) || 0; //Time in microseconds since page-load or 0 if unsupported
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = Math.random() * 16; //random number between 0 and 16
		if (d > 0) { //Use timestamp until depleted
			r = (d + r) % 16 | 0;
			d = Math.floor(d / 16);
		} else { //Use microseconds since page-load if supported
			r = (d2 + r) % 16 | 0;
			d2 = Math.floor(d2 / 16);
		}
		return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
	});
}
// 将数组转为对象
export function arrayToObject(arr, key = 'dictType') {
	var obj = {};
	if (arr&&arr.length > 0) {
		for (var i = 0; i < arr.length; i++) {
			obj[arr[i][key]] = arr[i];
		}
	}

	return obj;
}
// 日期格式化
export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

// 表单重置
export function resetForm(refName) {
	if (this.$refs[refName]) {
		this.$refs[refName].resetFields();
	}
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
	let search = params;
	search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};

	// 兼容多种调用方式：
	// 1) addDateRange(params, [start,end]) → 写入 beginTime/endTime
	// 2) addDateRange(params, [start,end], 'CreateTime') → 写入 beginCreateTime/endCreateTime
	// 3) addDateRange(params, [[s1,e1],[s2,e2]], ['CreateTime','FinishTime']) → 批量写入
	// 4) addDateRange(params, undefined, { CreateTime:[s1,e1], FinishTime:[s2,e2] }) → 批量写入（推荐）

	// 批量对象形态：propName 为对象 { Key: [start,end] }
	if (propName && typeof propName === 'object' && !Array.isArray(propName)) {
		Object.keys(propName).forEach(function(key){
			const dr = Array.isArray(propName[key]) ? propName[key] : [];
			search.params['begin' + key] = dr[0];
			search.params['end' + key] = dr[1];
		});
		return search;
	}

	// 批量数组形态：propName 为数组，dateRange 为同长度的二维数组
	if (Array.isArray(propName) && Array.isArray(dateRange)) {
		for (let i = 0; i < propName.length; i++) {
			const key = propName[i];
			const dr = Array.isArray(dateRange[i]) ? dateRange[i] : [];
			search.params['begin' + key] = dr[0];
			search.params['end' + key] = dr[1];
		}
		return search;
	}

	// 单个形态：与原逻辑保持一致
	dateRange = Array.isArray(dateRange) ? dateRange : [];
	if (typeof (propName) === 'undefined') {
		search.params['beginTime'] = dateRange[0];
		search.params['endTime'] = dateRange[1];
	} else {
		search.params['begin' + propName] = dateRange[0];
		search.params['end' + propName] = dateRange[1];
	}
	return search;
}

// 支持传入一个映射对象的多时间范围辅助方法
// 用法：addDateRanges(params, { CreateTime: [s1,e1], FinishTime: [s2,e2] })
export function addDateRanges(params, rangesMap) {
	return addDateRange(params, undefined, rangesMap);
}

// 回显数据字典
export function selectDictLabel(datas, value) {
	var actions = [];
	Object.keys(datas).some((key) => {
		if (datas[key].value == ('' + value)) {
			actions.push(datas[key].label);
			return true;
		}
	})
	return actions.join('');
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
	var actions = [];
	var currentSeparator = undefined === separator ? "," : separator;
	var temp = value.split(currentSeparator);
	Object.keys(value.split(currentSeparator)).some((val) => {
		Object.keys(datas).some((key) => {
			if (datas[key].dictValue == ('' + temp[val])) {
				actions.push(datas[key].dictLabel + currentSeparator);
			}
		})
	})
	return actions.join('').substring(0, actions.join('').length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
	var args = arguments, flag = true, i = 1;
	str = str.replace(/%s/g, function () {
		var arg = args[i++];
		if (typeof arg === 'undefined') {
			flag = false;
			return '';
		}
		return arg;
	});
	return flag ? str : '';
}

// 转换字符串，undefined,null等转化为""
export function praseStrEmpty(str) {
	if (!str || str == "undefined" || str == "null") {
		return "";
	}
	return str;
}

// 数据合并
export function mergeRecursive(source, target) {
	for (var p in target) {
		try {
			if (target[p].constructor == Object) {
				source[p] = mergeRecursive(source[p], target[p]);
			} else {
				source[p] = target[p];
			}
		} catch (e) {
			source[p] = target[p];
		}
	}
	return source;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of data) {
		let parentId = d[config.parentId];
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		nodeIds[d[config.id]] = d;
		childrenListMap[parentId].push(d);
	}

	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}



/**
 * 判断传入时间是否过期（是否早于当前时间）
 * @param {string|Date|number} targetTime - 待判断的时间（支持格式：YYYY-MM-DD、YYYY-MM-DD HH:MM:SS、时间戳、Date对象）
 * @param {boolean} [isEqualExpired=false] - 时间相等时是否视为过期（默认：false，即等于当前时间不算过期）
 * @returns {boolean} - 若过期返回 true，否则返回 false
 */
export function isTimeExpired(targetTime, isEqualExpired = false) {
  // 1. 处理目标时间，转换为时间戳（毫秒）
  let targetTimestamp;
  if (targetTime instanceof Date) {
    // 若传入的是 Date 对象，直接取时间戳
    targetTimestamp = targetTime.getTime();
  } else if (typeof targetTime === 'number') {
    // 若传入的是数字，视为时间戳（注意：若为10位需转为13位）
    targetTimestamp = targetTime.toString().length === 10 
      ? targetTime * 1000 
      : targetTime;
  } else if (typeof targetTime === 'string') {
    // 若传入的是字符串，尝试解析为 Date 对象
    const date = new Date(targetTime);
    if (isNaN(date.getTime())) {
      // 解析失败，抛出错误
      throw new Error(`无效的时间格式：${targetTime}，支持格式：YYYY-MM-DD、YYYY-MM-DD HH:MM:SS、时间戳`);
    }
    targetTimestamp = date.getTime();
  } else {
    throw new Error(`不支持的时间类型：${typeof targetTime}`);
  }

  // 2. 获取当前时间戳（毫秒）
  const currentTimestamp = Date.now();

  // 3. 对比时间（根据 isEqualExpired 决定是否包含等于的情况）
  if (isEqualExpired) {
    return targetTimestamp <= currentTimestamp;
  } else {
    return targetTimestamp < currentTimestamp;
  }
}


export const ak = 'shangchuanbeizhu'
